//
//  PPFoundSearchViewController.m
//  pickpic
//
//  Created by Jinxiao on 8/27/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPFoundSearchViewController.h"

#import "PPFoundSearchAlbumViewController.h"
#import "PPFoundSearchUserViewController.h"

#import "PPFoundSearchTableViewCell.h"

#import "PPAlbumModel.h"
#import "PPAlbumHotTagModel.h"
#import "PPAlbumRecentTagModel.h"

@interface PPFoundSearchViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>
@property (readwrite, nonatomic, strong) UITextField *searchField;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (readwrite, nonatomic, strong) NSArray *groups;

@property (readwrite, nonatomic, strong) NSString *keyword;
@property (readwrite, nonatomic, strong) NSNumber *tagID;
@end

@implementation PPFoundSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _searchField = [[UITextField alloc] init];
    _searchField.font = [UIFont systemFontOfSize:14];
    _searchField.textColor = [UIColor colorWithRGBHex:0xb2b2b2];
    _searchField.frame = CGRectMake(0, 0, 275, 25);
    _searchField.layer.cornerRadius = 5;
    _searchField.layer.masksToBounds = YES;
    _searchField.backgroundColor = [UIColor colorWithRGBHex:0xffffff alpha:0.1];
    _searchField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"搜索" attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14], NSForegroundColorAttributeName: [UIColor colorWithRGBHex:0x999999]}];
    _searchField.returnKeyType = UIReturnKeySearch;
    _searchField.delegate = self;

    UIImageView *iconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon-search"]];
    iconView.contentMode = UIViewContentModeScaleAspectFit;
    [iconView sizeToFit];
    iconView.width += 20;
    _searchField.leftView = iconView;
    _searchField.leftViewMode = UITextFieldViewModeAlways;

    self.navigationItem.titleView = _searchField;

    UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelItemDidPressed:)];
    self.navigationItem.rightBarButtonItem = cancelItem;

    dispatch_async(dispatch_get_main_queue(), ^{
        [_searchField becomeFirstResponder];
    });
}

- (void)cancelItemDidPressed:(UIBarButtonItem *)item {
    [self.view endEditing:YES];

    [self.navigationController popViewControllerAnimated:NO];
}

- (void)backItemDidPressed {
    [self.view endEditing:YES];

    [self.navigationController popViewControllerAnimated:NO];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 46;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _groups.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSDictionary *group = [_groups safeObjectAtIndex:section];

    NSArray *tags = [group validArrayForKey:@"tags"];

    return tags.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSDictionary *group = [_groups safeObjectAtIndex:section];

    NSString *title = [group validStringForKey:@"title"];

    return title;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PPFoundSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    NSDictionary *group = [_groups safeObjectAtIndex:indexPath.section];

    NSArray *tags = [group validArrayForKey:@"tags"];

    id tag = [tags safeObjectAtIndex:indexPath.row];

    cell.label.text = [tag name];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    NSDictionary *group = [_groups safeObjectAtIndex:indexPath.section];
    NSString *title = [group validStringForKey:@"title"];
    if ([title isEqualToString:@"最近搜索标签"]) {
        [MobClick event:@"117"];
    }
    else
    {
        [MobClick event:@"116"];
    }

    NSArray *tags = [group validArrayForKey:@"tags"];

    id tag = [tags safeObjectAtIndex:indexPath.row];

    [self performSearchWithKeyword:nil tag:tag];

    [_tableView.superview sendSubviewToBack:_tableView];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    [self reloadTags];

    [_tableView scrollRectToVisible:CGRectMake(0, 0, CGFLOAT_MIN, CGFLOAT_MIN) animated:NO];

    [_tableView.superview bringSubviewToFront:_tableView];

    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
        _tableView.alpha = 1;
    } completion:^(BOOL finished) {

    }];

    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if([string isEqualToString:@"\n"]) {

        NSString *keyword = [[textField.text stringByReplacingCharactersInRange:range withString:string] stringByRemovingLinebreaks];

        [self performSearchWithKeyword:keyword tag:nil];

        return NO;
    }

    return YES;
}

- (void)performSearchWithKeyword:(NSString *)keyword tag:(id)tag {
    [MobClick event:@"115"];
    [_searchField resignFirstResponder];

    _keyword = nil;
    _tagID = nil;

    NSNumber *tagID = nil;

    if(tag != nil) {
        if([tag respondsToSelector:@selector(name)]) {
            keyword = [tag name];
        }

        if([tag respondsToSelector:@selector(tagID)]) {
            tagID = [tag performSelector:@selector(tagID)];
        }
    }

    if(keyword.length == 0) {
        return;
    }

    _keyword = keyword;

    BOOL exists = NO;

    if(tagID != nil && [PPAlbumRecentTagModel find:@{@"tagID" : tagID}]) {
        exists = YES;
    }

    if(keyword != nil && [PPAlbumRecentTagModel find:@{@"name" : _keyword}]) {
        exists = YES;
    }

    if(!exists) {
        NSArray *recentTags = [PPAlbumRecentTagModel allWithOrder:@{@"index": @"asc"}];
        if(recentTags.count == 5) {
            PPAlbumRecentTagModel *tag = recentTags.firstObject;
            [tag delete];
        }
    }

    PPAlbumRecentTagModel *newTag = nil;

    if(tagID != nil) {
        newTag = [PPAlbumRecentTagModel existingAlbumRecentTagForTagID:tagID.integerValue];
    } else if(_keyword != nil) {
        newTag = [PPAlbumRecentTagModel existingAlbumRecentTagForTagName:keyword];
    }

    if(newTag != nil) {
        newTag.index = @(100);
        newTag.name = _keyword;
        newTag.tagID = _tagID;

        NSArray *recentTags = [PPAlbumRecentTagModel allWithOrder:@{@"index": @"asc"}];
        for(NSInteger index = 0; index < recentTags.count; index++) {
            PPAlbumRecentTagModel *tag = recentTags[index];
            tag.index = @(index);
        }
    }

    [[NSManagedObjectContext threadObjectContext] saveContext];

    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
        _tableView.alpha = _keyword.length == 0 ? 1 : 0;
    } completion:^(BOOL finished) {
        [self reloadContents];
    }];

    _searchField.text = _keyword;
}

- (void)reloadTags {
    NSMutableArray *groups = [NSMutableArray array];

    NSArray <PPAlbumRecentTagModel *> *recentTags = [PPAlbumRecentTagModel allWithOrder:@{@"index": @"desc"}];
    if(recentTags.count > 0) {
        [groups addObject:@{@"title": @"最近搜索标签", @"tags": recentTags}];
    }

    NSArray <PPAlbumHotTagModel *> *hotTags = [PPAlbumHotTagModel all];
    if(hotTags.count > 0) {
        [groups addObject:@{@"title": @"热门标签", @"tags": hotTags}];
    }

    _groups = groups;

    [_tableView reloadData];
}

- (void)transitIndicatorView:(UIView *)indicatorView fromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex {
    if(toIndex == 0) {
        [MobClick event:@"137"];
        indicatorView.backgroundColor = [UIColor colorWithRGBHex:0xef532a];
    } else {
        [MobClick event:@"138"];
        indicatorView.backgroundColor = [UIColor colorWithRGBHex:0x400090];
    }
}

- (CGFloat)preferredIndicatorHeight {
    return 3;
}

- (CGFloat)preferredIndicatorWidth {
    return self.view.width/2;
}

- (UIColor *)preferredIndicatorBackgroundColor {
    return [UIColor colorWithRGBHex:0xcccccc];
}

- (NSArray <NSString *> *)preferredTitles {
    return @[@"图册", @"用户"];
}

- (NSArray <UIViewController *> *)preferredViewControllers {
    if(_keyword == nil && _tagID == nil) {
        return nil;
    }

    PPFoundSearchAlbumViewController *albumViewController = [[PPFoundSearchAlbumViewController alloc] init];
    albumViewController.keyword = _keyword;

    PPFoundSearchUserViewController *userViewController = [[PPFoundSearchUserViewController alloc] init];
    userViewController.keyword = _keyword;

    return @[albumViewController, userViewController];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

@end
